package org.ala.tiktools.mybatis.commons;

import org.ala.tiktools.mybatis.spring.TikToolsMyBatisSpringContext;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author ala
 * @date 2025-01-08 13:17
 */
public class SqlSessionTemplateHolder {


    private static SqlSessionTemplate sqlSessionTemplate;

    public static SqlSessionTemplate newInstance() {
        SqlSessionFactory sf = TikToolsMyBatisSpringContext.getBean(SqlSessionFactory.class);
        return new SqlSessionTemplate(sf);
    }

    public static SqlSessionTemplate getInstance() {
        if (sqlSessionTemplate == null) {
            synchronized (SqlSessionTemplateHolder.class) {
                if (sqlSessionTemplate == null) {
                    try {
                        sqlSessionTemplate = TikToolsMyBatisSpringContext.getBean(SqlSessionTemplate.class);
                    } catch (Exception e) {
                        //  如果拿不到Bean则通过 SqlSessionFactory 初始化一个
                        //  SqlSessionFactory总有吧，不然写个der的sql
                        SqlSessionFactory sf = TikToolsMyBatisSpringContext.getBean(SqlSessionFactory.class);
                        sqlSessionTemplate = new SqlSessionTemplate(sf);
                    }
                }
            }
        }
        return sqlSessionTemplate;
    }
    public static void setInstance(SqlSessionTemplate tpl) {
        sqlSessionTemplate = tpl;
    }


    /**
     *  拿sql
     */
    public static BoundSql boundSql(String name, Object param) {
        Configuration c = TikToolsMyBatisSpringContext.getBeanWithAssert(Configuration.class);
        return c.getMappedStatement(name).getBoundSql(param);
    }
}
